package com.slipper.codeless.controller;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.slipper.core.file.FileServiceUtil;
import com.slipper.system.affix.bo.AffixItemBO;
import com.slipper.system.affix.service.AffixItemService;
import com.slipper.system.codeless.bo.AppVersionBO;
import com.slipper.system.codeless.service.AppVersionService;
import com.slipper.util.FileUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/app")
public class AppApiController {
    @Resource
    private AppVersionService appVersionService;
    @Resource
    private AffixItemService affixItemService;

    @GetMapping(value = "/{code}/{type}/version")
    public String version(@PathVariable("code") String code, @PathVariable("type") String type) {
        AppVersionBO appVersion = appVersionService.queryLatestBy(code, type);
        return appVersion == null ? "1.0.0" : appVersion.getVersion();
    }

    @GetMapping(value = "/{code}/{type}/download")
    public void download(
            HttpServletResponse response,
            @PathVariable("code") String code,
            @PathVariable("type") String type) throws Exception {
        AppVersionBO appVersion = appVersionService.queryLatestBy(code, type);
        if (appVersion == null) return;
        AffixItemBO affixItem = this.affixItemService.queryBy(appVersion.getFileId());
        if (affixItem == null) return;
        FileUtil.download(response, affixItem.getTrueName(), FileServiceUtil.readFile(affixItem.getSavePath()));
    }

    @PostMapping(value = "/qrcode")
    public void qrcode(HttpServletResponse response, @RequestBody Map<String, Object> data) throws Exception {
        if (data == null || !data.containsKey("url")) return;

        String url = (String) data.get("url");
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 0);
        BitMatrix matrix = new QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, 200, 200, hints);

        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/png;charset=UTF-8");
        MatrixToImageWriter.writeToStream(matrix, "jpeg", response.getOutputStream());
    }
}
